<?php
/**
 * Created by PhpStorm.
 * User: server
 * Date: 2019/5/22
 * Time: 15:53
 */

namespace app\admin\controller;

\think\Loader::import('controller/Controller', \think\Config::get('traits_path'), EXT);

use app\admin\Controller;
use think\Db;
use think\Config;
use think\Request;

class DriverSettlement extends Controller
{
    use \app\admin\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    /**
     * 首页
     * @return mixed
     */
    public function index()
    {

        $data = input();
        $map = [];
        $map['is_apply_settlement'] = 1;

        if (!empty($data['id'])) {
            $map['dtg.id'] = ['=', $data['id']];
        }

        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }

        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }

        if (!empty($data['mobile'])) {
            $map['au.mobile'] = ['like', "%{$data['mobile']}%"];
        }

        if (!empty($data['car_type'])) {
            $map['d.car_type'] = ['like', "%{$data['car_type']}%"];
        }

        if (!empty($data['plate_number'])) {
            $map['d.plate_number'] = ['like', "%{$data['plate_number']}%"];
        }

        $listRows = $this->request->param('numPerPage') ?: Config::get("paginate.list_rows");

        $list = Db::name('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_route r', 'r.id=dtg.route_id', 'left')
            ->join('tp_admin_user au', 'au.id=dtg.driver_user_id', 'left')
            ->join('tp_driver d', 'd.user_id=dtg.driver_user_id', 'left')
            ->join('tp_bank_card bc', 'bc.user_id=dtg.driver_user_id', 'left')
            ->field('dtg.*,r.title,au.realname,au.mobile,d.plate_number,d.car_type,bc.bank_name,bc.card_num')
            ->where($map)
            ->order('id desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);

        $new_list = $list->toArray()['data'];

        foreach ($new_list as $k => $v) {
            // 计算本次结算金额
            $new_list[$k]['this_settlement_money'] = $v['driver_fee'] + $v['driver_compensation'] + $v['company_compensation'] - $v['other_deduct_money'] - $v['deduct_money'];

            // 获取司机累计结算金额
            $total_settlement_money = Db::name('admin_user')
                ->where('id', $v['driver_user_id'])
                ->value('total_settlement_money');

            // 判断该派车单是否计算过
            if ($v['is_count'] !== 1) {
                // 没被计算过, 计算累计结算金额
                $new_list[$k]['total_settlement_money'] = $total_settlement_money + $new_list[$k]['this_settlement_money'];

                // 修改计算状态
                Db::name('dispatch_traveler_group')
                    ->where('id', $v['id'])
                    ->setField('is_count', 1);
            } else {
                // 直接使用累计结算金额
                $new_list[$k]['total_settlement_money'] = $total_settlement_money;
            }

            // 计算本次发票金额
            $new_list[$k]['this_invoice_money'] = Db::name('driver_invoice')
                ->where('dispatch_group_id', $v['id'])
                ->where('isdelete', 0)
                ->sum('total');

            // 计算累计发票金额
            $new_list[$k]['total_invoice_money'] = Db::name('driver_invoice')
                ->where('driver_user_id', $v['driver_user_id'])
                ->where('isdelete', 0)
                ->sum('total');

            if ($new_list[$k]['total_invoice_money'] < ($new_list[$k]['total_settlement_money']) * 0.7) {
                $invoice_condition = 1;
            } else {
                $invoice_condition = 0;
            }
            Db::name('dispatch_traveler_group')
                ->where('id', $v['id'])
                ->update([
                    'this_settlement_money' => $new_list[$k]['this_settlement_money'],
                    'this_invoice_money' => $new_list[$k]['this_invoice_money'],
                    'invoice_condition' => $invoice_condition
                ]);
            Db::name('admin_user')
                ->where('id', $v['driver_user_id'])
                ->update([
                    'total_settlement_money' => $new_list[$k]['total_settlement_money'],
                    'total_invoice_money' => $new_list[$k]['total_invoice_money'],
                ]);
        }

        $list = Db::name('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_route r', 'r.id=dtg.route_id', 'left')
            ->join('tp_admin_user au', 'au.id=dtg.driver_user_id', 'left')
            ->join('tp_driver d', 'd.user_id=dtg.driver_user_id', 'left')
            ->join('tp_bank_card bc', 'bc.user_id=dtg.driver_user_id', 'left')
            ->field('dtg.*,r.title,au.realname,au.mobile,d.plate_number,d.car_type,bc.bank_name,bc.card_num,au.total_settlement_money,au.total_invoice_money')
            ->where($map)
            ->where('invoice_condition', 0)
            ->order('id desc')
            ->paginate($listRows, false, ['query' => $this->request->get()]);
//        dump($list);
        $this->view->assign('list', $list);
        $this->view->assign("count", $list->total());
        $this->view->assign("page", $list->render());
        $this->view->assign('numPerPage', $list->listRows());
        return $this->view->fetch();
    }

    /**
     * 电子表格
     * @return mixed
     */

    public function get_excel(Request $request)
    {
        $data = input();
        ini_set('max_execution_time', 3600);//1小时
        ini_set('memory_limit', '500M');
        Vendor('PHPExcel.PHPExcel');
        Vendor('PHPExcel.PHPExcel.WorkSheet.Drawing');
        Vendor('PHPExcel.PHPExcel.Writer.Excel2007');
        //实例化
        $export_excel = new \PHPExcel();
        //设置文档属性
        $writer = \PHPExcel_IOFactory::createWriter($export_excel, 'Excel2007');
        //设置内容
        $export_sheet = $export_excel->getActiveSheet();
        for ($l = 0; $l < 26; $l++) {
            $letter[] = chr($l + 65);
        }
        $countChr = count($letter);
        for ($j = 0; $j < $countChr; $j++) {
            for ($k = 0; $k < $countChr; $k++) {
                $letter[] = $letter[$j] . $letter[$k];
            }
        }
        $tableHeader = ['派车单号', '路线名称', '司机姓名', '联系号码', '车型', '车牌号', '出发日期', '结束日期', '申请结算日期', '司机费用', '司机补偿金', '公司补偿金', '差评扣款', '扣其他费用', '本次结算金额', '开户银行卡支行', '银行卡号', '累计结算金额', '累计发票金额', '已交发票金额', '备注'];
        $tableLength = count($tableHeader);
        for ($i = 0; $i < $tableLength; $i++) {
            $export_sheet->setCellValue("$letter[$i]1", "$tableHeader[$i]");
            $export_sheet->getColumnDimension("$letter[$i]")->setWidth(20);
        }
        $map = array();
        $map['is_apply_settlement'] = 1;

        if (!empty($data['id'])) {
            $map['dtg.id'] = ['=', $data['id']];
        }

        if (!empty($data['title'])) {
            $map['r.title'] = ['like', "%{$data['title']}%"];
        }

        if (!empty($data['realname'])) {
            $map['au.realname'] = ['like', "%{$data['realname']}%"];
        }

        if (!empty($data['mobile'])) {
            $map['au.mobile'] = ['like', "%{$data['mobile']}%"];
        }

        if (!empty($data['car_type'])) {
            $map['d.car_type'] = ['like', "%{$data['car_type']}%"];
        }

        if (!empty($data['plate_number'])) {
            $map['d.plate_number'] = ['like', "%{$data['plate_number']}%"];
        }

        //选择导出数据
        if ($data['id']) {
            $id = implode($data['id'], ',');
            $map['dtg.id'] = ['in', $id];
        }

        $list = Db::name('dispatch_traveler_group')
            ->alias('dtg')
            ->join('tp_route r', 'r.id=dtg.route_id', 'left')
            ->join('tp_admin_user au', 'au.id=dtg.driver_user_id', 'left')
            ->join('tp_driver d', 'd.user_id=dtg.driver_user_id', 'left')
            ->join('tp_bank_card bc', 'bc.user_id=dtg.driver_user_id', 'left')
            ->field('dtg.id,r.title,au.realname,au.mobile,d.car_type,d.plate_number,dtg.go_date,dtg.end_date,dtg.apply_settlement_time,dtg.driver_fee,dtg.driver_compensation,dtg.company_compensation,dtg.deduct_money,dtg.other_deduct_money,dtg.this_settlement_money,bc.bank_name,bc.card_num,au.total_settlement_money,au.total_invoice_money,dtg.this_invoice_money,dtg.remark')
            ->where($map)
            ->where('invoice_condition', 0)
            ->order('dtg.id desc')
            ->select();

        foreach ($list as $k => $v) {

            if ($v['go_date']) {
                $list[$k]['go_date'] = date('Y-m-d H:i:s', $v['go_date']);
            }
            if ($v['end_date']) {
                $list[$k]['end_date'] = date('Y-m-d H:i:s', $v['end_date']);
            }
            if ($v['apply_settlement_time']) {
                $list[$k]['apply_settlement_time'] = date('Y-m-d H:i:s', $v['apply_settlement_time']);
            }

        }
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        //定义table键
        if (!empty($list)) {
            $tableKey = array_keys($list[0]);
            //填充表格信息
            $tableKeyLength = count($tableKey);
            foreach ($list as $tk => $tv) {
                $tk += 2;
                for ($i = 0; $i < $tableKeyLength; $i++) {
                    $export_sheet->setCellValue("$letter[$i]" . $tk, $tv[$tableKey[$i]]);
                }
            }
        }
        $fileName = date('YmdHis', time()) . "司机结算-司机结算数据.xls";
        $fileName = iconv('utf-8', 'gb2312', $fileName);
        ob_end_clean();
        if ($request->isGet()) {
            header('Content-Type:application/force-download');
            header('Content-Type:application/octet-stream');
            header('Content-Type:application/download');
            header('Content-Disposition:inline;filename=' . $fileName);
            header('Content-Transfer-Encoding:binary');
            header('Cache-Control:must-revalidate,post-check=0');
            header('Pragma:no-cache');
            $writer->save('php://output');
            exit();
        } else {
            // 保存文件到服务器上
            $path = ROOT_PATH . "public/excel";
            // 判断文件是否存在
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $fileName = iconv('gb2312', 'utf-8', $fileName);
            $file = $path . "/{$fileName}";
            $writer->save($file);
            $url = $request->domain() . "/excel/{$fileName}";
            return ajax_return_adv($url, '', '', '', '', '', 5);
        }
    }
}